package com.iqiyi.config;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * AOP事务管理配置类
 */
//@Configuration
//@Aspect
public class TransationConfig {
    //定义切点变量 拦截service下类的所有方法
    private static final String AOP_POINTCUI = "execution (* com.iqiyi.service.*.*(..))";
    @Autowired
    private PlatformTransactionManager transactionManager;
    @Bean
    public TransactionInterceptor txAdvice(){
        //事务管理规则,声明事务管理的方法名
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        //设置事务
        RuleBasedTransactionAttribute readOnlyRule = new RuleBasedTransactionAttribute();
        //设置事务为只读事务
        readOnlyRule.setReadOnly(true);
        //定义事务的隔离级别
        //transactiondefinition 定义事务的隔离级别；
        //PROPAGATION_NOT_SUPPORTED事务传播级别5，不支持事务
        readOnlyRule.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
        //设置事务
        RuleBasedTransactionAttribute requireRule = new RuleBasedTransactionAttribute();
        //抛出异常后执行切点回滚
        requireRule.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
        //定义事务的隔离级别
        //PROPAGATION_REQUIRED:事务隔离性为1
        //假如当前正要执行的事务不再另一个事务里,name就重新创建一个新的事务
        requireRule.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        Map<String, TransactionAttribute> txMap=new HashMap<>();
        txMap.put("add*",requireRule);
        txMap.put("update*",requireRule);
        txMap.put("delete*",requireRule);
        txMap.put("insert*",requireRule);
        txMap.put("find*",readOnlyRule);
        txMap.put("select*",readOnlyRule);
        txMap.put("count*",readOnlyRule);
        source.setNameMap(txMap);

        return new TransactionInterceptor(transactionManager,source);
    }
    @Bean
    public Advisor txAdviceAdvisor(){
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUI);
        return new DefaultPointcutAdvisor(pointcut,txAdvice());
    }
}
